﻿//------------------------------------------------------------------------------
// The contents of this file are subject to the Microsoft Public License (Ms-PL)
// You may obtain a copy of the License at http://psadmin.codeplex.com/license. 
// 
// Software distributed under the License is distributed on an "AS IS" basis, 
// WITHOUT WARRANTY OF ANY KIND, either express or implied. 
// See the License for the specific language governing rights and limitations 
// under the License.
// 
// The initial developer is Ben Foster (ben.foster@retroviz.com)
// Copyright (c) Retroviz Limited (http://www.retroviz.com).
// All Rights Reserved.
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using StructureMap;
using StructureMap.Configuration.DSL;
using PSAdmin.Core.Interfaces;
using PSAdmin.Core.Domain;
using PSAdmin.Services;
using PSAdmin.Data.Repositories;
using NHibernate;

namespace PSAdmin.Web.Infrastructure
{
    public class Bootstrapper : IBootstrapper
    {
        private static bool _hasStarted;
        
        public void BootstrapStructureMap() {
            ObjectFactory.Initialize(x => {
                x.AddRegistry(new AppRegistry());
            });

            // execute startup tasks

            var tasks = ObjectFactory.GetAllInstances<IStartUpTask>()
                .Where(x => x.IsEnabled);

            foreach (var task in tasks)
                task.Execute();
        }

        public static void Restart()
        {
            if (_hasStarted) {
                ObjectFactory.ResetDefaults();
            } else {
                Boot();
                _hasStarted = true;
            }
        }

        public static void Boot() {
            new Bootstrapper().BootstrapStructureMap();
        }
    }

    public class AppRegistry : Registry
    {
        public AppRegistry() {

            For<ISessionStore>().Use<HttpSessionStore>();
            
            // repos
            For<ISession>().TheDefault.Is.ConstructedBy(x => Global.SessionFactory.GetCurrentSession());
            For<IPSScriptRepository>().Use<PSScriptRepository>();
            For<IUserRoleRepository>().Use<UserRoleRepository>();
            For<IUserEventRepository>().Use<UserEventRepository>();
            
            // services
            For<ILoggerService>().Use<Log4NetLoggerService>();
            For<ITemplateService>().Use<NVelocityTemplateService>();
            For<IScriptService>().Use<PSScriptService>();

            Scan(x => {
                x.Assembly("PSAdmin.Services");
                x.TheCallingAssembly();
                x.AddAllTypesOf<IStartUpTask>();
                x.WithDefaultConventions();
            });
        }
    }
}
